package com.lmx.repoDomain.repository;

import io.katharsis.repository.annotations.JsonApiResourceRepository;
import io.katharsis.repository.annotations.JsonApiSave;

import java.util.Date;

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lmx.common.constants.CommonConstants;
import com.lmx.common.context.ActionContextHolder;
import com.lmx.common.util.CommonUtil;
import com.lmx.persistence.service.NursingService;
import com.lmx.repoDomain.exception.BusinessException;
import com.lmx.repoDomain.tmodel.CustomerNursingPlanModel;

@JsonApiResourceRepository(CustomerNursingPlanModel.class)
@Component
public class CustomerNursingPlanModelRepository extends BaseRepository<CustomerNursingPlanModel> {

	@Autowired
	protected NursingService nursingService;

	@PostConstruct
	public void init() {
		dslJpaService.setEntityClass(CustomerNursingPlanModel.class);
	}

	@Override
	@JsonApiSave
	public CustomerNursingPlanModel save(CustomerNursingPlanModel record) {
		if (ActionContextHolder.getPlanModelList().contains(record.getRemark())) {
			// throw new BusinessException(null,
			// CommonConstants.ERROR_CODE.ADD_ERROR.label(), null);
		} else {
			ActionContextHolder.getPlanModelList().add(record.getRemark());
		}

		if ("0".equals(record.getExeType())) {
			Date dateTemp = new Date();
			int weekIndex = CommonUtil.getWeekIndexFromSun(dateTemp);
			int year = dateTemp.getYear() + 1900;// 产生 年 周 序号
			int weekTab = CommonUtil.getWeek(dateTemp);
			// 验证当天护理计划是否被执行过
			int copyNowFlag = nursingService.checkPlanDetailNowRelations(
					new Long(record.getRemark()), year, weekIndex, weekTab);
			if (copyNowFlag > 0) {
				throw new BusinessException(null, CommonConstants.ERROR_CODE.REPEAT_ERROR.label(),
						null);
			}
		}

		// 删除老人护理模版以及未来周护理计划#删除原有并新增模版
		nursingService.deletePlanItemByCustomerId(Long.parseLong(record.getRemark()));
		// ActionContextHolder.getPlanModelList().remove(record.getRemark());
		record = super.save(record);

		if ("0".equals(record.getExeType())) { // 立即生效
			// 将模版复制到今天
			nursingService.copyPlanToToday(record, new Long(record.getRemark()));
		}

		return record;
	}

}
